import jwt from 'jsonwebtoken'
import authConfig from '../config/auth'
import { env } from '../config/commonConfig'
import { isEmail, isMobile } from '../utils/tool'
import {
  rsaDecrypt,
  encryptPassword,
  comparePassword,
  getEncrypt,
  getDecrypt
} from '../utils/key'
import Models from '../database/models'
const auth = authConfig[env]
/**
 * @author kntt
 * 用户注册
 * @param {string} username
 * @param {string} password
 * @returns {object} status 200 成功
 * @returns {object} status 500 服务器错误
 * @returns {object} status 501 用户名已存在
 * @returns {object} status 504 手机号或邮箱不正确
 */
export const userRegisiter = async (req, res) => {
  let { username, password } = req.body
  let user
  try {
    user = await Models.Users.findOne({
      where: {
        $or: {
          email: username,
          phone: getEncrypt(username)
        }
      }
    })
  } catch (error) {
    res.json({
      status: 500,
      message: '服务器发生错误！'
    })
  }

  if (!user) {
    password = rsaDecrypt(password)
    if (isEmail(username) || isMobile(username)) {
      password = await encryptPassword(password)
      let user = await Models.Users.create({
        email: isEmail(username) && username,
        phone: isMobile(username) && getEncrypt(username),
        password,
        update_time: new Date(),
        create_time: new Date()
      })
      res.json({
        status: 200,
        message: 'success',
        data: jwt.sign({ id: user.id }, auth.secret, {
          expiresIn: auth.expiresIn
        })
      })
    } else {
      res.json({
        status: 504,
        message: '请输入正确的邮箱或手机号码!',
        data: null
      })
    }
  } else {
    res.json({
      status: 501,
      message: '用户名已存在！',
      data: null
    })
  }
}

/**
 * @author kntt
 * 用户登录
 * @param {string} username
 * @param {string} password
 * @returns {object} status 200 成功
 * @returns {object} status 500 服务器错误
 * @returns {object} status 502 用户名不存在
 * @returns {object} status 503 用户名密码不匹配
 */
export const userLogin = async (req, res) => {
  let { username, password } = req.body
  let user
  try {
    user = await Models.Users.findOne({
      where: {
        $or: {
          email: username,
          phone: getEncrypt(username)
        }
      }
    })
  } catch (error) {
    res.json({
      status: 500,
      message: error.message
    })
  }

  if (user) {
    try {
      // 对比 用户输入密码和储存密码是否相同
      let isTrue = await comparePassword(rsaDecrypt(password), user.password)
      if (isTrue) {
        res.json({
          status: 200,
          message: 'success',
          data: jwt.sign({ id: user.id }, auth.secret, {
            expiresIn: 1 * 60
          })
        })
      } else {
        res.json({
          status: 503,
          message: '用户名或密码错误！',
          data: null
        })
      }
    } catch (error) {
      res.json({
        status: 500,
        message: '服务器发生错误！'
      })
    }
  } else {
    res.json({
      status: 502,
      message: '用户名不存在！',
      data: {}
    })
  }
}

/**
 * @author kntt
 * 用户信息
 * @returns {object} status 200 成功
 * @returns {object} status 500 服务器错误
 * @returns {object} status 502 用户不存在
 */
export const userInfo = async (req, res) => {
  let { id } = jwt.verify(req.headers.authorization.split(' ')[1], auth.secret)
  let user
  try {
    user = await Models.Users.findOne({
      attributes: ['email', 'avatar', 'age', 'gender', 'wechat', 'phone'],
      where: {
        id
      }
    })
    if (user) {
      res.json({
        status: 200,
        message: 'success',
        data: user
      })
    } else {
      res.json({
        status: 502,
        message: '用户不存在！',
        data: null
      })
    }
  } catch (error) {
    res.json({
      status: 500,
      message: error.message
    })
  }
}

/**
 * @author kntt
 * 用户登出
 * @returns {object} status 200 成功
 * @returns {object} status 500 服务器错误
 */
export const userLogout = async (req, res) => {
  // let { id } = jwt.verify(req.headers.authorization.split(' ')[1], auth.secret)
  try {
    res.json({
      status: 200,
      message: 'success',
      data: null
    })
  } catch (error) {
    res.json({
      status: 500,
      message: error.message
    })
  }
}
